package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.helper.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.sql.Wrapper;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper,ApUser> implements ApUserService {

    @Override
    public ResponseResult login(LoginDto dto) {
        //登录
       if(!(StringUtil.isBlank(dto.getPhone())&& StringUtil.isBlank(dto.getPassword()))){
           ApUser dbuser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
           if(dbuser == null){
               return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
           }
           //取盐
           String salt = dbuser.getSalt();
           String password = dto.getPassword();
           log.info("password：{}",password);
           //盐加密
           log.info("密码：{}",dbuser.getPassword());
           String pwd = DigestUtils.md5DigestAsHex((password + salt).getBytes());
           log.info("加密密码：{}",pwd);
           if (!pwd.equals(dbuser.getPassword())){
               return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
           }
           String token = AppJwtUtil.getToken(dbuser.getId().longValue());
           Map<String,Object>  map=new HashMap<>();
           map.put("token",token);
           dbuser.setSalt("");
           dbuser.setPassword("");
           map.put("user",dbuser);
           return ResponseResult.okResult(map);
       }else{
           //游客登录
          Map<String,Object> map =new HashMap<>();
          map.put("token", AppJwtUtil.getToken(0L));
          return ResponseResult.okResult(map);
       }




    }
}
